package com.qf.springbootproject.shopcart.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qf.springbootproject.shopcart.entity.ShoppingCart;
import com.qf.springbootproject.shopcart.service.ShoppingCartService;
import com.qf.springbootproject.utils.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 购物车  前端控制器
 * </p>
 *
 * @author yyq
 * @since 2023-02-16
 */
@RestController
@RequestMapping("/shopcart")
@CrossOrigin
public class ShoppingCartController {
    @Autowired
    ShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @RequestMapping("/add")
    public ResultVo add(@RequestBody ShoppingCart shoppingCart) {
        //添加购物车日期
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = simpleDateFormat.format(new Date());
        shoppingCart.setCartTime(dateStr);
        shoppingCartService.save(shoppingCart);
        return ResultVo.ok();
    }

    /**
     * 购物车接口
     *
     * @param userId
     * @return
     */
    @RequestMapping("/list")
    public ResultVo list(Integer userId) {
        List<ShoppingCart> data = shoppingCartService.listShopCart(userId);
        return ResultVo.ok(data);
    }

    /**
     * 更新购物车商品数量
     *
     * @param cid
     * @param cnum
     * @return
     */
    @PutMapping("/update/{cid}/{cnum}")
    public ResultVo update(@PathVariable("cid") Integer cid, @PathVariable("cnum") Integer cnum) {
        //更新方法
        //shoppingCartService.update(new UpdateWrapper<ShoppingCart>().set("cart_num", cnum).eq("cart_id", cid));
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setCartId(cid);
        shoppingCart.setCartNum(cnum + "");
        shoppingCartService.updateCardNum(shoppingCart);
        return ResultVo.ok();
    }

    @RequestMapping("/listbycids")
    public ResultVo listbycids(Integer[] cids) {
        List<ShoppingCart> shoppingCartList = shoppingCartService.listbycids(cids);
        return ResultVo.ok(shoppingCartList);

    }
}









